package com.business.dynamic.task;

import com.business.common.utils.FileUploadUtil;
import com.business.common.utils.StrKit;
import com.business.dynamic.entity.Dynamic;
import com.business.redis.constant.RedisKeyConstant;
import com.business.redis.utils.RedisKeysUtil;
import com.business.redis.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class ScheduledTask {

    private Logger logger = LoggerFactory.getLogger(ScheduledTask.class);

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 每天1点执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(fixedRate = 100000)
    public void run() {
        //更新热门标签
        try {
            this.updateHotTag();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        try {
            deleteTempImage();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    private void updateHotTag() {
        logger.info("更新热门标签定时任务开始");
        String key  = RedisKeyConstant.USER_DETAILS_HOT_TAG_LIST2+"*";;
        Set<String> keys = RedisUtil.keys(key);
        keys.iterator().forEachRemaining(k -> {

            long size = RedisUtil.getZSetSize(key);
            //删除不热门的标签
            if (size > 20) {
                RedisUtil.removeZSetByScore(key, 0, 1);
            } else if (size > 100) {
                RedisUtil.removeZSetByScore(key, 0, 2);
            } else if (size > 1000) {
                RedisUtil.removeZSetByScore(key, 0, 3);
            }

        });
        logger.info("更新热门标签定时任务结束");
    }

    /**
     * 删除多余的图片
     */
    private void deleteTempImage() {
        logger.info("删除多余图片开始");
        AtomicInteger count = new AtomicInteger();
        Set<String> keys = RedisUtil.keys(String.format(RedisKeyConstant.DYNAMIC_UPLOAD_IMAGES,"*"));
        keys.iterator().forEachRemaining((k) -> {
            String userId = k.substring(k.lastIndexOf(":")+1);
            if (StrKit.isBlank(userId)) {
                return;
            }
            String addTokenKey = String.format(RedisKeyConstant.DYNAMIC_ADD_TOKEN, userId);
            if (!RedisUtil.hasKey(addTokenKey)) {
                //需要删除的图片
                String imageKey = String.format(RedisKeyConstant.DYNAMIC_UPLOAD_IMAGES,userId);
                Set<String> urls = RedisUtil.getSetValues(imageKey);
                urls.iterator().forEachRemaining(u -> {
                    logger.info("删除图片:" + u);
                    fileUploadUtil.delFile(u);
                    count.getAndIncrement();
                });
                RedisUtil.delValue(imageKey);
            }
        });
        logger.info("删除多余图片结束,一共删除了" + count + "张图片");
    }

}
